#pragma once
#include <unordered_map>
#include <string>
#include <fstream>
#include "log.hpp"
#include "lockguard.hpp"

class Dict
{
private:
    bool load(std::string& filepath)
    {
        ifstream in(filepath.c_str());
        if(!in.is_open())
        {
            LOG(FATAL, "filepath isn't opened fatally!");
            return false;
        }
        std::string line;
        while(getline(in, line))
        {
            size_t len = line.size();
            if(len == 0) //读到了空行
                continue;
            size_t pos = line.find(": ");
            if(pos == string::npos) //npos就是-1，最大的无符号数
                continue;
            string english = line.substr(0, pos);
            string chinese = line.substr(pos+2, len-pos-1);
            if(english.empty() || chinese.empty())
                continue;
            LOG(DEBUG, "%s:%s", english.c_str(), chinese.c_str());

            _dict.insert(make_pair(english, chinese));
            line.clear();
        }
        LOG(DEBUG, "total is %d items!", _dict.size());
        in.close();
        return true;
    }

public:
    Dict(std::string filepath)
    {
        if(!load(filepath))
        {
            LOG(FATAL, "load dict fatally!");
            exit(1);
        }
        LOG(FATAL, "load dict successly!");
    }

    std::string translate(std::string str)
    {
        std::unordered_map<std::string, std::string>::iterator it = _dict.find(str);
        if(it == _dict.end())
        {
            LOG(FATAL, "find isn't seccessful!");
            return "nullptr";
        }
        return it->second;
    }

    ~Dict()
    {

    }
private:
    std::unordered_map<std::string, std::string> _dict;
};